package com.example.social.viewmodel

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.social.api.ApiClient.commentApiService
import com.example.social.api.ApiClient.threadApiService
import com.example.social.api.BaseResponse
import com.example.social.api.CommentList
import com.example.social.api.ThreadList
import com.example.social.model.CommentModel
import com.example.social.model.ThreadModel
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class HomeViewModel : ViewModel() {

    private val _threadsAndUsers = MutableLiveData<List<ThreadList>>(emptyList())
    val threadsAndUsers: LiveData<List<ThreadList>> = _threadsAndUsers

    private val _thread = MutableLiveData<ThreadModel>(null)
    val thread: LiveData<ThreadModel> = _thread




    private val _comment = MutableLiveData<List<CommentModel>>(emptyList())
    val comment: LiveData<List<CommentModel>> = _comment

    private val _error = MutableLiveData<String>()
    val error: LiveData<String> get() = _error

    private val _errorShown = MutableLiveData(false)
    val isErrorShown: LiveData<Boolean> get() = _errorShown

    // 设置错误信息
    fun setError(message: String) {
        _error.value = message
        _errorShown.value = false // 每次设置新错误时重置
    }

    // 标记错误信息已经显示
    fun markErrorAsShown() {
        _errorShown.value = true
    }

    init {
        fetchThreadsAndUsers {
            _threadsAndUsers.value = it
        }
    }


    private fun fetchThreadsAndUsers(onResult: (List<ThreadList>) -> Unit) {
        val call = threadApiService.getAllThread()
        call.enqueue(object : Callback<BaseResponse<List<ThreadList>>> {
            override fun onResponse(
                call: Call<BaseResponse<List<ThreadList>>>,
                response: Response<BaseResponse<List<ThreadList>>>
            ) {
                if (response.isSuccessful) {
                    val data = response.body()?.data
                    // 确保 data 不为 null，并检查 thread 和 users 字段是否有效
                    val nonNullData =
                        data?.filter { it.threads != null && it.users != null } ?: emptyList()
                    if (nonNullData.isNotEmpty()) {
                        onResult(nonNullData)
                    } else {
                        Log.e("fetchThreadsAndUsers", "数据为空.")
                    }
                } else {
                    Log.e("fetchThreadsAndUsers", "系统异常")
                }
            }

            override fun onFailure(call: Call<BaseResponse<List<ThreadList>>>, t: Throwable) {
                Log.e("fetchThreadsAndUsers", "请求失败", t)
            }
        })
    }

    fun getComments(threadId: String) {
        val call = commentApiService.getCommentByTid(threadId)
        call.enqueue(object : Callback<BaseResponse<List<CommentModel>>> {
            override fun onResponse(
                call: Call<BaseResponse<List<CommentModel>>>,
                response: Response<BaseResponse<List<CommentModel>>>
            ) {
                if (response.isSuccessful && response.body()?.code == 0) {
                    Log.e("getComments", response.body()?.data.toString())
                    _comment.postValue(response.body()!!.data)
                } else {
                    Log.e("getComments", "请求失败")
                }
            }

            override fun onFailure(call: Call<BaseResponse<List<CommentModel>>>, t: Throwable) {
                Log.e("getComments", "请求失败", t)
            }

        })
    }

    fun postComment(tid: String, uid: String, content: String) {
        val call = commentApiService.addComment(CommentList(tid, uid, content))
        call.enqueue(object : Callback<BaseResponse<String>> {
            override fun onResponse(
                call: Call<BaseResponse<String>>,
                response: Response<BaseResponse<String>>
            ) {
                if (response.isSuccessful && response.body()!!.code == 0) {
                    setError("添加评论成功!")
                    getComments(tid)  // 强制刷新评论数据
                } else {
                    setError("添加失败")
                    Log.e("postComment", "请求失败")
                }
            }

            override fun onFailure(call: Call<BaseResponse<String>>, t: Throwable) {
                setError("添加失败,请检查网络设置")
                Log.e("postComment", "请求失败", t)
            }

        })
    }

    fun getAllThreadCommentByUserId(userId: String) {
        val call = commentApiService.getAllThreadCommentByUserId(userId)
        call.enqueue(object : Callback<BaseResponse<List<CommentModel>>> {
            override fun onResponse(
                call: Call<BaseResponse<List<CommentModel>>>,
                response: Response<BaseResponse<List<CommentModel>>>
            ) {
                if (response.isSuccessful && response.body()?.code == 0) {
                    _comment.postValue(response.body()!!.data)
                } else {
                    Log.e("getAllThreadCommentByUserId", "请求失败,请检查网络设置")
                }
            }

            override fun onFailure(call: Call<BaseResponse<List<CommentModel>>>, t: Throwable) {
                Log.e("getAllThreadCommentByUserId", "系统错误", t)
            }

        })
    }

    fun getThreadsByTid(tid: String) {
        val call = threadApiService.getThreadsByTid(tid)
        call.enqueue(object : Callback<BaseResponse<ThreadModel>> {
            override fun onResponse(
                call: Call<BaseResponse<ThreadModel>>,
                response: Response<BaseResponse<ThreadModel>>
            ) {
                if (response.isSuccessful) {
                    // 处理成功响应
                    _thread.postValue(response.body()?.data)
                    Log.e("getThreadsByTid", response.body()?.data.toString())
                } else {
                    Log.e("getThreadsByTid", "请求失败")
                }
            }

            override fun onFailure(call: Call<BaseResponse<ThreadModel>>, t: Throwable) {
                Log.e("getThreadsByTid", "请求失败", t)
            }
        })
    }

    fun getListFollowThreadById(userId: String) {
        val call = threadApiService.getListFollowThreadById(userId)
        call.enqueue(object : Callback<BaseResponse<List<ThreadList>>> {
            override fun onResponse(
                call: Call<BaseResponse<List<ThreadList>>>,
                response: Response<BaseResponse<List<ThreadList>>>
            ) {
                if (response.isSuccessful && response.body()!!.code == 0) {
                    _threadsAndUsers.postValue(response.body()!!.data)
                    Log.e("getListFollowThreadById",_threadsAndUsers.toString())
                }else{
                    Log.e("getListFollowThreadById", "请求失败")
                }
            }

            override fun onFailure(call: Call<BaseResponse<List<ThreadList>>>, t: Throwable) {
                Log.e("getListFollowThreadById", "请求失败",t)
            }

        })
    }


}
